<template>
	<el-button
		:type="type"
		:size="size"
		:plain="plain"
		:round="round"
		:circle="circle"
		:loading="loading"
		:disabled="isSend || disabled"
		:icon="icon"
		:autofocus="autofocus"
		@click="onSendHandle"
	>
		{{ label }}
	</el-button>
</template>

<script>
import pattern from '@/utils/pattern';
export default {
	props: {
		//接收验证码的手机
		defaultSecond: {
			type: Number,
			default: 60,
		},
		tel: {
			type: String,
			default: '',
		},
		type: {
			type: String,
			default: 'primary',
		},
		size: {
			type: String,
			default: '',
		},
		plain: {
			type: Boolean,
			default: false,
		},
		round: {
			type: Boolean,
			default: false,
		},
		circle: {
			type: Boolean,
			default: false,
		},
		loading: {
			type: Boolean,
			default: false,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		icon: {
			type: String,
			default: '',
		},
		autofocus: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			isSend: false,
			label: '发送验证码',
			sec: this.defaultSecond,
		};
	},
	created() {
		this.timer = null;
	},
	methods: {
		//发送验证码
		onSendHandle() {
			if (!this.tel) {
				this.$notify.error({
					title: '操作失败',
					message: '请输入手机号码后，再点击发送验证码',
				});
				return;
			}

			if (!pattern.tel.test(this.tel)) {
				this.$notify.error({
					title: '操作失败',
					message: '手机号码格式不正确，请输入正确的手机号码',
				});
				return;
			}

			//发送ajax请求
			this.isSend = true;

			this.startCountDown(() => {
				this.isSend = false;
			});
		},

		//启动倒计时
		startCountDown(cb) {
			clearInterval(this.timer);
			this.timer = setInterval(() => {
				this.sec--;
				this.label = `${this.sec}s后重新发送`;
				if (this.sec <= 0) {
					clearInterval(this.timer);
					this.sec = this.defaultSecond;
					this.label = '发送验证码';
					cb && cb();
				}
			}, 1000);
		},
	},
};
</script>

<style lang="scss" scoped></style>
